﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Custom.Controls
{
    public class LoadingManager
    {
        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern bool ShowWindow(HandleRef hWnd, int nCmdShow);

        private static LoadingManager manager = null;
        private LoadingForm loadingForm = null;
        public delegate void DoWork();

        public static LoadingManager Instance
        {
            get
            {
                if (manager == null)
                {
                    manager = new LoadingManager();
                }

                return manager;
            }
        }

        /// <summary>
        /// 显示进度窗口
        /// </summary>
        /// <param name="owner"></param>
        /// <param name="work"></param>
        public void Show(Form owner, DoWork work, string description = "请稍等")
        {
            loadingForm = new LoadingForm(description);
            if (owner != null)
            {
                loadingForm.StartPosition = FormStartPosition.CenterParent;
            }
            else
            {
                loadingForm.StartPosition = FormStartPosition.CenterScreen;
            }

            Task.Factory.StartNew(() =>
            {
                work.Invoke();
            });

            loadingForm.ShowDialog(owner);
        }

        public void Close()
        {
            if (loadingForm != null && loadingForm.IsHandleCreated)
            {
                loadingForm.Close();
                loadingForm = null;
            }
        }

        public void CloseAysnc(Form owner)
        {
            if (owner != null && loadingForm != null)
            {
                try
                {
                    owner.Invoke(new Action(() =>
                    {
                        loadingForm.Opacity = 0;
                        loadingForm.Close();
                        loadingForm = null;
                    }));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }

    }
}
